/**********************************************************************
*  Copyright (c) 2007 - Victor Jacobs - victor.jacobs@gmail.com
*
*  Permission is hereby granted, free of charge, to any person
*  obtaining a copy of this software and associated documentation
*  files (the "Software"), to deal in the Software without
*  restriction, including without limitation the rights to use,
*  copy, modify, merge, publish, distribute, sublicense, and/or sell
*  copies of the Software, and to permit persons to whom the
*  Software is furnished to do so, subject to the following
*  conditions:
*
*  The above copyright notice and this permission notice shall be
*  included in all copies or substantial portions of the Software.
*
*  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
*  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
*  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
*  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
*  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
*  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
*  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
*  OTHER DEALINGS IN THE SOFTWARE.
**********************************************************************/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using Vj.Ann;
using System.IO;

namespace Vj.AnnApp
{
    public partial class AnnApp : Form
    {
        public AnnApp()
        {
            InitializeComponent();
        }

        #region Data Fields
        
        private List<Pattern> patternList;
        private BaseNetwork network;

        #endregion
        
        #region On Load

        private void AnnApp_Load(object sender, EventArgs e)
        {
            patternList = new List<Pattern>();
            Random rg = new Random();

            #region Create Training Patterns
            
            int numOfPatterns = (int)Math.Pow(2.0, 2.0 * 5.0);
            
            List<Pattern> patternsToTest = PatternBuilder.ONESPattern(5, numOfPatterns);
            
            for (int i = 0; i < 10000; i++)
            {
                int next = rg.Next(numOfPatterns);
                patternList.Add(patternsToTest[next]);
            }

            #endregion

            #region Create Network

            network = BaseNetwork.Create(new int[] { 5, 7, 1 }, (double)learningRateUpDown.Value, 0.0, 1.0);
            graphPictureBox1.Network = network;

            graphPictureBox1.DrawAllValues = false;
            graphPictureBox1.DrawNetwork = false;
            graphPictureBox1.DrawOnlyOutputValues = false;

            #endregion

        }
        #endregion

        #region Train/Propogate

        private void trainButton_Click(object sender, EventArgs e)
        {
            DateTime EventTime1 = DateTime.Now;

            outputTextBox.Text += "Working ...";

            for (int i = 0; i < patternList.Count; i++)
            {
                network.Train(patternList[i]);

                // update status here
                if (i % 1000 == 0)
                {
                    outputTextBox.Text += ".";
                    outputTextBox.Refresh();
                }
            }

            graphPictureBox1.Network = network;
            
            DateTime EventTime2 = DateTime.Now;
            TimeSpan elapsed = EventTime2 - EventTime1;

            outputTextBox.Text += "\r\n";
            outputTextBox.Text += "Training Time: " + elapsed.TotalSeconds;
            outputTextBox.Text += "\r\n\r\n";

            SaveScreenshot();
        }

        private void propogateButton_Click(object sender, EventArgs e)
        {
            Pattern testPattern = new Pattern(5, 1);
            testPattern.Inputs = new double[] { 1.0, 1.0, 0.0, 1.0, 1.0 };
            testPattern.Outputs = new double[] { 0.8 };

            network.Test(testPattern);
            graphPictureBox1.Network = network;

            outputTextBox.Text += "Expected: " + network.OutputLayer.Neurons[0].ExpectedValue;
            outputTextBox.Text += "\r\n";

            outputTextBox.Text += "Actual: " + network.OutputLayer.Neurons[0].Output;
            outputTextBox.Text += "\r\n\r\n";

            SaveScreenshot();
        }

        private void resetButton_Click(object sender, EventArgs e)
        {
            network = BaseNetwork.Reset();
            graphPictureBox1.Network = network;
            graphPictureBox1.Refresh();
        }

        #endregion

        #region Network Configuration Options

        private void scaleNumericUpDown_ValueChanged(object sender, EventArgs e)
        {
            graphPictureBox1.ScaleValue = (float)scaleNumericUpDown.Value;
            graphPictureBox1.Refresh();
        }

        
        #endregion

        #region Display Options Menu

        private void drawNetworkToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (drawNetworkToolStripMenuItem.Checked)
                graphPictureBox1.DrawNetwork = true;
            else
                graphPictureBox1.DrawNetwork = false;
        }
        
        private void displayOutputToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (displayOutputToolStripMenuItem.Checked)
            {
                displayAllValuesToolStripMenuItem.Checked = false;
                graphPictureBox1.DrawOnlyOutputValues = true;
            }
            else
            {
                graphPictureBox1.DrawOnlyOutputValues = false;
            }

        }

        private void displayAllValuesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (displayAllValuesToolStripMenuItem.Checked)
            {
                displayOutputToolStripMenuItem.Checked = false;
                graphPictureBox1.DrawAllValues = true;
            }
            else
            {
                graphPictureBox1.DrawAllValues = false;
            }

        }

        #endregion

        #region Utility Methods

        private void SaveScreenshot()
        {
            if (!Directory.Exists(@"C:\Graphs"))
                Directory.CreateDirectory(@"C:\Graphs");

            Bitmap bm = new Bitmap(graphPictureBox1.Width, graphPictureBox1.Height);
            graphPictureBox1.DrawToBitmap(bm, new Rectangle(graphPictureBox1.Location, graphPictureBox1.Size));

            bm.Save(@"C:\Graphs\graphimage.bmp");
        }

        #endregion

 
        private void createButton_Click(object sender, EventArgs e)
        {
            patternList = new List<Pattern>();
            Random rg = new Random();

            #region Create Training Patterns

            int numOfInputsInPattern = 5;
            int numOfOutputsInPattern = 1;

            int numOfPatterns = (int)Math.Pow(2.0, 2.0 * numOfInputsInPattern);

            List<Pattern> patternsToTest = PatternBuilder.ONESPattern(numOfInputsInPattern, numOfPatterns);

            for (int i = 0; i < (int)trainingCyclesNumericUpDown.Value; i++)
            {
                int next = rg.Next(numOfPatterns);
                patternList.Add(patternsToTest[next]);
            }

            #endregion

            #region Create Network

            network = BaseNetwork.Create(new int[] { (int)nodesPerInputLayerUpDown.Value, 7, (int)nodesPerOutputLayerUpDown.Value }, 
                (double)learningRateUpDown.Value, 0.0, 1.0);

            graphPictureBox1.Network = network;

            #endregion

        }

        private void layerCountNumericUpDown_ValueChanged(object sender, EventArgs e)
        {
            hiddenLayerUpDown2.Enabled = true;
            hiddenLayerUpDown3.Enabled = true;
            hiddenLayerUpDown4.Enabled = true;
            hiddenLayerUpDown5.Enabled = true;

            if (layerCountNumericUpDown.Value < 5)
                hiddenLayerUpDown5.Enabled = false;

            if (layerCountNumericUpDown.Value < 4)
                hiddenLayerUpDown4.Enabled = false;

            if (layerCountNumericUpDown.Value < 3)
                hiddenLayerUpDown3.Enabled = false;

            if (layerCountNumericUpDown.Value < 2)
                hiddenLayerUpDown2.Enabled = false;



        }


    }
}